// Service Worker - 缓存策略和离线支持
const CACHE_NAME = 'time-collector-v1.0.0'
const STATIC_CACHE = 'static-v1.0.0'
const DYNAMIC_CACHE = 'dynamic-v1.0.0'
const API_CACHE = 'api-v1.0.0'

// 需要缓存的静态资源
const STATIC_ASSETS = [
    '/',
    '/index.html',
    '/manifest.json',
    '/favicon.ico',
    '/src/assets/contact-avatar.svg',
    '/src/assets/beian.png'
]

// 需要缓存的API路径
const API_PATTERNS = [
    '/api/posts',
    '/api/categories',
    '/api/tags',
    '/api/friends',
    '/api/comments'
]

// 安装事件 - 缓存静态资源
self.addEventListener('install', event => {
    console.log('Service Worker: Installing...')

    event.waitUntil(
        caches.open(STATIC_CACHE)
        .then(cache => {
            console.log('Service Worker: Caching static assets')
            return cache.addAll(STATIC_ASSETS)
        })
        .then(() => {
            console.log('Service Worker: Static assets cached')
            return self.skipWaiting()
        })
        .catch(error => {
            console.error('Service Worker: Failed to cache static assets', error)
        })
    )
})

// 激活事件 - 清理旧缓存
self.addEventListener('activate', event => {
    console.log('Service Worker: Activating...')

    event.waitUntil(
        caches.keys()
        .then(cacheNames => {
            return Promise.all(
                cacheNames.map(cacheName => {
                    if (cacheName !== STATIC_CACHE &&
                        cacheName !== DYNAMIC_CACHE &&
                        cacheName !== API_CACHE) {
                        console.log('Service Worker: Deleting old cache', cacheName)
                        return caches.delete(cacheName)
                    }
                })
            )
        })
        .then(() => {
            console.log('Service Worker: Activated')
            return self.clients.claim()
        })
    )
})

// 拦截请求 - 实现缓存策略
self.addEventListener('fetch', event => {
    const { request } = event
    const url = new URL(request.url)

    // 跳过非GET请求
    if (request.method !== 'GET') {
        return
    }

    // 跳过扩展和开发者工具请求
    if (url.protocol === 'chrome-extension:' || url.hostname === 'localhost') {
        return
    }

    // 静态资源缓存策略 - Cache First
    if (isStaticAsset(request.url)) {
        event.respondWith(cacheFirst(request, STATIC_CACHE))
        return
    }

    // API请求缓存策略 - Network First with Cache Fallback
    if (isApiRequest(request.url)) {
        event.respondWith(networkFirst(request, API_CACHE))
        return
    }

    // 动态内容缓存策略 - Stale While Revalidate
    event.respondWith(staleWhileRevalidate(request, DYNAMIC_CACHE))
})

// 判断是否为静态资源
function isStaticAsset(url) {
    const staticExtensions = ['.js', '.css', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.ico', '.woff', '.woff2', '.ttf', '.eot']
    return staticExtensions.some(ext => url.includes(ext)) ||
        STATIC_ASSETS.some(asset => url.includes(asset))
}

// 判断是否为API请求
function isApiRequest(url) {
    return API_PATTERNS.some(pattern => url.includes(pattern))
}

// Cache First 策略 - 优先使用缓存，缓存不存在时从网络获取
async function cacheFirst(request, cacheName) {
    try {
        const cachedResponse = await caches.match(request)
        if (cachedResponse) {
            console.log('Service Worker: Serving from cache', request.url)
            return cachedResponse
        }

        const networkResponse = await fetch(request)
        if (networkResponse.ok) {
            const cache = await caches.open(cacheName)
            cache.put(request, networkResponse.clone())
            console.log('Service Worker: Cached new resource', request.url)
        }

        return networkResponse
    } catch (error) {
        console.error('Service Worker: Cache First failed', error)
        return new Response('Network error', { status: 503 })
    }
}

// Network First 策略 - 优先从网络获取，网络失败时使用缓存
async function networkFirst(request, cacheName) {
    try {
        const networkResponse = await fetch(request)
        if (networkResponse.ok) {
            const cache = await caches.open(cacheName)
            cache.put(request, networkResponse.clone())
            console.log('Service Worker: Cached API response', request.url)
        }
        return networkResponse
    } catch (error) {
        console.log('Service Worker: Network failed, trying cache', request.url)
        const cachedResponse = await caches.match(request)
        if (cachedResponse) {
            return cachedResponse
        }
        return new Response('Offline - No cached data available', { status: 503 })
    }
}

// Stale While Revalidate 策略 - 立即返回缓存，同时在后台更新缓存
async function staleWhileRevalidate(request, cacheName) {
    const cache = await caches.open(cacheName)
    const cachedResponse = await cache.match(request)

    const fetchPromise = fetch(request).then(networkResponse => {
        if (networkResponse.ok) {
            cache.put(request, networkResponse.clone())
            console.log('Service Worker: Updated cache', request.url)
        }
        return networkResponse
    }).catch(error => {
        console.error('Service Worker: Network request failed', error)
    })

    return cachedResponse || fetchPromise
}

// 消息处理 - 用于与主线程通信
self.addEventListener('message', event => {
    if (event.data && event.data.type === 'SKIP_WAITING') {
        self.skipWaiting()
    }

    if (event.data && event.data.type === 'GET_CACHE_INFO') {
        event.ports[0].postMessage({
            type: 'CACHE_INFO',
            cacheNames: ['static', 'dynamic', 'api']
        })
    }
})

// 推送通知处理
self.addEventListener('push', event => {
    console.log('Service Worker: Push notification received')

    const options = {
        body: event.data ? event.data.text() : 'New notification',
        icon: '/src/assets/contact-avatar.svg',
        badge: '/src/assets/contact-avatar.svg',
        vibrate: [100, 50, 100],
        data: {
            dateOfArrival: Date.now(),
            primaryKey: 1
        },
        actions: [{
                action: 'explore',
                title: '查看详情',
                icon: '/src/assets/contact-avatar.svg'
            },
            {
                action: 'close',
                title: '关闭',
                icon: '/src/assets/contact-avatar.svg'
            }
        ]
    }

    event.waitUntil(
        self.registration.showNotification('博客通知', options)
    )
})

// 通知点击处理
self.addEventListener('notificationclick', event => {
    console.log('Service Worker: Notification clicked')

    event.notification.close()

    if (event.action === 'explore') {
        event.waitUntil(
            clients.openWindow('/')
        )
    }
})